#!/bin/sh
# ***************************************************************************
# bootstrap : Set up config.mak
# ***************************************************************************
# Copyright (C) 2003-2009 the VideoLAN team
# $Id$
#
# Authors: Christophe Massiot <massiot@via.ecp.fr>
#          Derk-Jan Hartman <hartman at videolan dot org>
#          Felix Paul Kühne <fkuehne at videolan dot org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
# ***************************************************************************

LANG=C
export LANG
set -e
set +x

usage()
{
cat << EOF
usage: $0 [-t target] [-d distro] [-b buildir] [-i installdir]

OPTIONS:
   -t target     Force target to "target"
   -d distro     Force distro to "distro"
   -b buildir    Set build dir to "builddir"
   -i installdir Install to "installdir"
   -h            Show some help
EOF
}

add_makefile_cfg()
{
    echo $1 >> "${config_mak}"
}

add_enabled_makefile_cfg()
{
    echo "$1=1" >> "${config_mak}"
}

error()
{
    echo "[contrib] ERROR: $1"
}

info()
{
    echo "[contrib] $1"
}

DISTRO=

hint_distro()
{
    # Give a hint about the auto detected distro
    if test -z "${DISTRO}"; then DISTRO="$1"; fi
}

BUILDDIR=.

while getopts "ht:d:b:i:" OPTION
do
     case $OPTION in
         h)
             usage
             exit 1
             ;;
         t)
             TARGET=$OPTARG
             ;;
         d)
             DISTRO=$OPTARG
             ;;
         b)
             BUILDDIR=$OPTARG
             ;;
         i)
             PREFIX=$OPTARG
             ;;
         ?)
             usage
             exit 1
             ;;
     esac
done
shift $(($OPTIND - 1))

if [ "x$1" != "x" ]; then
    error "Fallback to old command line switch, use the -t option now"
    TARGET="$1"
fi
if [ "x$2" != "x" ]; then
    usage
    exit 1
fi

BUILD=`gcc -dumpmachine`

if test "x$TARGET" = "x"; then
    TARGET="$BUILD"
    info "No target specified, using '$TARGET'"
fi

if test "x$PREFIX" = "x"; then
    PREFIX="`pwd`/hosts/$TARGET"
    info "No install dir specified, using '$PREFIX'"
fi

# Make sure prefix is absolute and existing
mkdir -p "${PREFIX}"
PREFIX=`cd "${PREFIX}" && pwd`
mkdir -p "${PREFIX}/share/aclocal" # aclocal needs this dir to exist

#
# Set up build dir
#

mkdir -p "${BUILDDIR}"

# Install build dir makefile
ln -sf "`pwd`/contrib.mak" "${BUILDDIR}/Makefile"

# Create the 'build-src' folder to build from source
mkdir -p "${BUILDDIR}/build-src"
ln -sf "`pwd`/src/contrib-src.mak" "${BUILDDIR}/build-src/Makefile"
ln -sf "`pwd`/src/packages.mak" "${BUILDDIR}/build-src/"
ln -sf "`pwd`/src/Patches" "${BUILDDIR}/build-src/"

# Create config.mak
config_mak="${BUILDDIR}/config.mak"
rm -f "${config_mak}"
{
    echo "# Automatically generated by bootstrap."
    echo "# Make changes if you know what you're doing."
} > "${config_mak}"

if test "$TARGET" != "$BUILD"; then
    test -z "$CC"    && CC="${TARGET}-gcc"
    test -z "$CXX"   && CXX="${TARGET}-g++"
    test -z "$LD"    && LD="${TARGET}-ld"
    test -z "$RANLIB"&& RANLIB="${TARGET}-ranlib"
    test -z "$AR"    && AR="${TARGET}-ar"
    test -z "$STRIP" && STRIP="${TARGET}-strip"
fi

case $TARGET in
    *powerpc*|*ppc*)
         ARCH="ppc"
     ;;
    *86_64*)
          ARCH="x86_64"
     ;;
    *86*)
          ARCH="i386"
     ;;
    arm*eabi)
          ARCH="armel"
     ;;
    arm*)
          ARCH="arm"
     ;;
esac
add_makefile_cfg "ARCH = $ARCH"

# Check the HAVE_{OS}
case $TARGET in
    *darwin*)
        add_enabled_makefile_cfg "HAVE_DARWIN_OS"
        add_enabled_makefile_cfg "HAVE_BSD"
    ;;
    *linux*)
        add_enabled_makefile_cfg "HAVE_LINUX"
    ;;
    *bsd*)
        add_enabled_makefile_cfg "HAVE_BSD"
    ;;
    *wince*)
        add_enabled_makefile_cfg "HAVE_WINCE"
    ;;
    *symbian*)
        add_enabled_makefile_cfg "HAVE_SYMBIAN"
    ;;
esac

# Figure out the correct distro to use
case $TARGET in
    ppc-darwin|*-apple-darwin8)
        error "Your version of Mac OS X is too old!"
        error "Compiling and running VLC requires 10.5.x or later"
        exit 1
    ;;
    powerpc-apple-darwin9)
        hint_distro macosx32
        HAVE_DARWIN_32=1

        CFLAGS_TUNING=" -arch ppc -mtune=G4"
        EXTRA_LDFLAGS=" -arch ppc"
    ;;
    i686-apple-darwin*)
        hint_distro macosx32
        HAVE_DARWIN_32=1

        CFLAGS_TUNING=" -march=prescott -mtune=generic -arch i386 -m32"
        EXTRA_LDFLAGS=" -arch i386"
    ;;
    x86_64-apple-darwin*)
        hint_distro macosx64
        HAVE_DARWIN_64=1

        CFLAGS_TUNING=" -march=core2 -mtune=core2 -m64 -arch x86_64"
        EXTRA_LDFLAGS=" -arch x86_64"
    ;;
    *mingw32ce)
        EXTRA_CPPFLAGS=" -D_WIN32_WCE=0x0500"
        hint_distro wince
    ;;
    *64-*mingw*)
        add_enabled_makefile_cfg "HAVE_WIN32"
        EXTRA_CFLAGS="-O3"
        hint_distro win64
    ;;
    *mingw32*)
        EXTRA_CFLAGS=" -O3 -march=i686 -mtune=generic"
        hint_distro win32
    ;;
    i686-pc-cygwin)
        add_enabled_makefile_cfg "HAVE_CYGWIN"
        CC="gcc -mno-cygwin -isystem /usr/include/mingw"
        CXX="g++ -mno-cygwin -isystem /usr/include/mingw"
        TARGET=`$CC -dumpmachine`
        EXTRA_CFLAGS=" -mno-cygwin -isystem /usr/include/mingw"
        EXTRA_CPPFLAGS=" -mno-cygwin -isystem /usr/include/mingw"
        EXTRA_LDFLAGS=" -mno-cygwin"
        hint_distro win32
    ;;
    arm-wince-pe)
        EXTRA_CPPFLAGS=" -D_WIN32_WCE"
        hint_distro wince
    ;;
    armeb-linux-uclibc)
        add_enabled_makefile_cfg "HAVE_UCLIBC"
        add_enabled_makefile_cfg "HAVE_BIGENDIAN"
        EXTRA_CFLAGS="-Os -march=armv5 -msoft-float"
    ;;
    arm-none-linux-gnueabi)
        if test -f /etc/maemo_version; then
            hint_distro maemo5
            EXTRA_CFLAGS=" -mcpu=cortex-a8 -mtune=cortex-a8 -march=armv7-a"
            EXTRA_CFLAGS="$EXTRA_CFLAGS -mfpu=neon -mfloat-abi=softfp"
            EXTRA_CFLAGS="$EXTRA_CFLAGS -O3 -fno-tree-vectorize"
        fi
    ;;
    *86_64*linux*)
        EXTRA_CFLAGS=" -fPIC"
        EXTRA_CPPFLAGS=" -fPIC"
        EXTRA_LDFLAGS=" -L/usr/lib64"
        add_makefile_cfg "LIBRARY_PATH = /usr/lib64"
        add_makefile_cfg "PKG_CONFIG_PATH = /usr/lib64/pkgconfig"
        add_makefile_cfg "PKG_CONFIG_LIBDIR = /usr/lib64/pkgconfig"
    ;;
esac

#
# Fix up the Distro
#

if test -z "${DISTRO}" -a "$TARGET" = "$BUILD"; then
    if test -d "/usr/lib/pkgconfig"; then
        if test -z "$PKG_CONFIG_PATH"; then
            add_makefile_cfg "PKG_CONFIG_PATH = /usr/lib/pkgconfig"
        fi
        if test -z "$PKG_CONFIG_LIBDIR"; then
            add_makefile_cfg "PKG_CONFIG_LIBDIR = /usr/lib/pkgconfig"
        fi
    fi
    # Try to match distribution
    if test -f /etc/fedora-release; then
        hint_distro fedora
    elif test -f /etc/maemo_version; then
        hint_distro maemo5
    elif test "$SBOX_UNAME_MACHINE"; then
        hint_distro maemo6
    elif test -f /etc/debian_version; then
        # NOTE: check for Debian *after* its derivatives
        hint_distro debian
    fi
fi

# Default Unix-like systems
hint_distro unix

distro_mak="${BUILDDIR}/distro.mak"
distro_file="`pwd`/src/Distributions/${DISTRO}.mak"
ln -sf "${distro_file}" "${distro_mak}"

#
# Distro specific settings
#

case "$DISTRO" in
  ios)
    if test -z "$IOS_SDK_ROOT"; then
        error "The bootstrap script requires the IOS_SDK_ROOT environment "
        error "variable to be set when building for iOS"
        exit 1
    fi
    add_makefile_cfg "IOS_SDK_ROOT = ${IOS_SDK_ROOT}"
    ;;
  macosx*)
    SDK_TARGET=10.5
    HAVE_MACOSX_DARWIN_9=1
    EXTRA_LDFLAGS="${EXTRA_LDFLAGS} -isysroot \${MACOSX_SDK} -Wl,-syslibroot,\${MACOSX_SDK} -mmacosx-version-min=\${SDK_TARGET}"
    EXTRA_CFLAGS="${EXTRA_CFLAGS} -D\${ENVP} -isysroot \${MACOSX_SDK} -mmacosx-version-min=\${SDK_TARGET}"
    CC="/usr/bin/gcc-4.2"
    CXX="/usr/bin/g++-4.2"
    LD="ld"
    RANLIB="ranlib"
    AR=
    STRIP="strip"
    add_makefile_cfg "PATH = /bin:/usr/bin:/usr/local/bin"
    add_makefile_cfg "SDK_TARGET = ${SDK_TARGET}"
    add_makefile_cfg "ENVP = MACOSX_DEPLOYMENT_TARGET=${SDK_TARGET}"
    add_makefile_cfg "MACOSX_SDK = /Developer/SDKs/MacOSX${SDK_TARGET}.sdk"
    add_enabled_makefile_cfg "HAVE_MACOSX"

    case $TARGET in
    x86_64*|i686*) add_enabled_makefile_cfg "HAVE_MACOSX_ON_INTEL" ;;
    esac
    case $TARGET in
    *darwin10)     add_enabled_makefile_cfg "HAVE_MACOSX_DARWIN_10" ;;
    *darwin9)      add_enabled_makefile_cfg "HAVE_MACOSX_DARWIN_9" ;;
    esac

    if ! test -e /Developer/SDKs; then
        error "Your Developer Tools' SDKs were not found.\nYou need to add extra symbolic links to /Developer to achieve correctly\nbuilt contribs.\nHave a look at the OSX-Compile-HOWTO for details." >&2
        exit 1
    fi
    ;;
  win*)
    add_makefile_cfg "PKG_CONFIG_PATH = \$(PREFIX)/lib/pkgconfig"
    ;;
  android)
    if test -z "$ANDROID_NDK"; then
        error "The bootstrap script requires the ANDROID_NDK environment variable "
        error "to be set when building for Android"
        exit 1
    fi
    # The given host (arm-eabi) is not the real one (arm-linux-androideabi)
    ln -sfn $TARGET hosts/arm-linux-androideabi
    CC="arm-linux-androideabi-gcc -nostdlib -lc -lgcc"
    CXX="arm-linux-androideabi-g++ -nostdlib -lc -lgcc"
    NM=arm-linux-androideabi-nm
    AR=arm-linux-androideabi-ar
    LD=arm-linux-androideabi-ld
    RANLIB=arm-linux-androideabi-ranlib
    STRIP=arm-linux-androideabi-strip
    # Add the PATH to the NDK
    add_makefile_cfg "ANDROID_NDK = ${ANDROID_NDK}"
    add_makefile_cfg "PATH = ${ANDROID_NDK}/toolchains/arm-linux-androideabi-4.4.3/prebuilt/linux-x86/bin/:${PATH}"
    add_enabled_makefile_cfg "HAVE_LINUX"
    if test -z "$NO_NEON"; then
        add_enabled_makefile_cfg "HAVE_NEON"
    fi
esac

# Save passed flags
EXTRA_CFLAGS="$EXTRA_CFLAGS $CFLAGS"
EXTRA_LDFLAGS="$EXTRA_LDFLAGS $LDFLAGS"
EXTRA_CPPFLAGS="$EXTRA_CPPFLAGS $CPPFLAGS"
EXTRA_CXXFLAGS="$EXTRA_CXXFLAGS $CXXFLAGS"

uppercase_distro=`echo "$DISTRO" | tr '[:lower:]' '[:upper:]'`
add_enabled_makefile_cfg "HAVE_${uppercase_distro}"
add_makefile_cfg "BUILD = $BUILD"
add_makefile_cfg "HOST = $TARGET"
add_makefile_cfg "SRCDIR = `pwd`"
add_makefile_cfg "PREFIX = ${PREFIX}"
add_makefile_cfg "VLCROOTDIR = `pwd`/../.."

ln -sfn hosts/$TARGET build

add_makefile_cfg "CC = ${CC}"
add_makefile_cfg "CXX = ${CXX}"
add_makefile_cfg "LD = ${LD}"
add_makefile_cfg "RANLIB = ${RANLIB}"
add_makefile_cfg "AR = ${AR}"
add_makefile_cfg "STRIP = ${STRIP}"
add_makefile_cfg "EXTRA_CFLAGS = ${CFLAGS_TUNING} ${EXTRA_CFLAGS}"
add_makefile_cfg "EXTRA_CPPFLAGS = ${EXTRA_CPPFLAGS} -isystem \$(PREFIX)/include"
add_makefile_cfg "EXTRA_LDFLAGS = ${EXTRA_LDFLAGS}"
add_makefile_cfg "EXTRA_PATH = ${EXTRA_PATH}"

#CMAKE
toolchain_cmake="${BUILDDIR}/toolchain.cmake"
rm -f ${BUILDDIR}/toolchain.cmake
if test ${DISTRO} = "win32"; then
    echo "SET(CMAKE_SYSTEM_NAME Windows)" >> "${toolchain_cmake}"
    echo "SET(CMAKE_RC_COMPILER ${TARGET}-windres)" >> "${toolchain_cmake}"
fi
case "$DISTRO" in macosx*)
    echo "SET(CMAKE_SYSTEM_NAME Darwin)" >> "${toolchain_cmake}"
    echo "set(CMAKE_C_FLAGS ${CFLAGS_TUNING} ${EXTRA_CFLAGS})" >> "${toolchain_cmake}"
    echo "set(CMAKE_CXX_FLAGS ${CFLAGS_TUNING} ${EXTRA_CFLAGS})" >> "${toolchain_cmake}"
    echo "set(CMAKE_LD_FLAGS ${EXTRA_LDFLAGS})" >> "${toolchain_cmake}"
esac
echo "SET(CMAKE_C_COMPILER ${CC})" >> "${toolchain_cmake}"
echo "SET(CMAKE_CXX_COMPILER ${CXX})" >> "${toolchain_cmake}"
echo "SET(CMAKE_FIND_ROOT_PATH  `pwd` )" >> "${toolchain_cmake}"
echo "set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)" >> "${toolchain_cmake}"
echo "set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)" >> "${toolchain_cmake}"
echo "set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)" >> "${toolchain_cmake}"

if wget --version >/dev/null 2>&1; then
    add_makefile_cfg "WGET = \"`which wget`\" -c --passive"
elif test -z `curl --version >/dev/null 2>&1`; then
    add_makefile_cfg "WGET = \"`which curl`\" -L -O"
else
    error "You need at least wget or curl to fetch the packages."
    exit 1
fi

if svn --version >/dev/null 2>&1; then
    add_makefile_cfg "SVN = \"`which svn`\""
else
    error "You do not have a subversion client in your PATH."
fi

if git --version>/dev/null 2>&1; then
    add_makefile_cfg "GIT = \"`which git`\""
else
    error "You do not have a Git client in your PATH."
fi

if test -z "$CONTRIBS_RELEASE"; then
    add_makefile_cfg "EXTRA_CFLAGS += -DNDEBUG"
    info "*****************************************************************"
    info "* If you need contribs with all debug information, run this     *"
    info "* line and compile the libraries on your own.                   *"
    info "* CONTRIBS_RELEASE=no ./bootstrap                               *"
    info "*****************************************************************"
fi

if test $HAVE_MACOSX_DARWIN_9; then
    add_enabled_makefile_cfg "HAVE_MACOSX_DARWIN_9"
    if ! /usr/bin/gcc-4.2 --version>/dev/null 2>&1; then
        error "You do not have GCC-4.2 installed in /usr/bin, compilation WILL FAIL."
    fi
fi

if test "$DISTRO" = "macosx32"; then
    info "*****************************************************************"
    info "* VLC will be compiled in 32bit mode using the 10.5 & later SDK.*"
    info "*                                                               *"
    info "* Re-run with the -t x86_64-apple-darwin* argument to turn on   *"
    info "* 64bit compilation for Intel-based Macs, whereas * is either   *"
    info "* 9 or 10 depending on your Darwin version.                     *"
    info "* There is no PPC64 support.                                    *"
    info "*****************************************************************"
fi

if test "$DISTRO" = "macosx64"; then
    info
    info "*****************************************************************"
    info "* VLC will be compiled in 64bit mode using the 10.5 & later SDK.*"
    info "*****************************************************************"
fi

case `uname` in
    Linux)
        CPUS=`grep -c ^processor /proc/cpuinfo`
     ;;
#    Darwin)
#        CPUS=`sysctl hw.ncpu|cut -d: -f2`
#    ;;
    *)
        CPUS=1  # default
     ;;
esac
add_makefile_cfg "MAKEFLAGS += -j$CPUS"

info "Using $CPUS processor(s)"
